import React, { useState, useRef, useEffect, useCallback } from 'react'
import './VerifyModal.css'

interface VerifyModalProps {
  isOpen: boolean
  onClose: () => void
  onSuccess: () => void
}

const VerifyModal: React.FC<VerifyModalProps> = ({ isOpen, onClose, onSuccess }) => {
  const [sliderValue, setSliderValue] = useState(0)
  const [isDragging, setIsDragging] = useState(false)
  const [verifyStatus, setVerifyStatus] = useState<'idle' | 'success' | 'error'>('idle')
  const [gapPosition, setGapPosition] = useState(0.6) // 缺口位置比例（0-1之间）
  const sliderRef = useRef<HTMLDivElement>(null)

  // 生成随机缺口位置
  const generateRandomGapPosition = () => {
    // 缺口位置在30%-80%之间随机，避免太靠边
    const minPosition = 0.3
    const maxPosition = 0.8
    return Math.random() * (maxPosition - minPosition) + minPosition
  }

  // 重置状态
  const resetVerification = useCallback(() => {
    setSliderValue(0)
    setVerifyStatus('idle')
    setIsDragging(false)
    setGapPosition(generateRandomGapPosition()) // 每次重置时生成新的随机位置
  }, [])

  // 处理滑块拖动
  const handleSliderMove = useCallback((clientX: number) => {
    if (!sliderRef.current) return
    
    const rect = sliderRef.current.getBoundingClientRect()
    const maxWidth = rect.width - 40 // 减去滑块宽度
    const newValue = Math.max(0, Math.min(maxWidth, clientX - rect.left - 20))
    
    setSliderValue(newValue)
    
    // 移除接近缺口时的绿色提示框逻辑
  }, [])

  // 检查验证结果
  const checkVerification = useCallback(() => {
    if (!sliderRef.current) return
    
    const rect = sliderRef.current.getBoundingClientRect()
    const maxWidth = rect.width - 40
    const puzzlePosition = sliderValue * 0.8
    const currentGapPosition = maxWidth * gapPosition // 使用动态缺口位置
    const distance = Math.abs(puzzlePosition - currentGapPosition)
    
    // 更严格的验证：拼图块中心必须与缺口中心对齐（容差3px）
    if (distance < 3) {
      setVerifyStatus('success')
      setTimeout(() => {
        onSuccess()
        onClose()
        resetVerification()
      }, 1000)
    } else {
      setVerifyStatus('error')
      // 验证失败后自动重置
      setTimeout(() => {
        resetVerification()
      }, 2000)
    }
  }, [sliderValue, gapPosition, onSuccess, onClose, resetVerification])

  // 鼠标事件处理
  const handleMouseDown = (e: React.MouseEvent) => {
    setIsDragging(true)
    handleSliderMove(e.clientX)
  }

  // 触摸事件处理
  const handleTouchStart = (e: React.TouchEvent) => {
    setIsDragging(true)
    handleSliderMove(e.touches[0].clientX)
  }

  const handleTouchMove = (e: React.TouchEvent) => {
    if (isDragging) {
      e.preventDefault()
      handleSliderMove(e.touches[0].clientX)
    }
  }

  const handleTouchEnd = () => {
    setIsDragging(false)
    checkVerification()
  }

  // 全局鼠标事件监听，让拖动更流畅
  useEffect(() => {
    const handleGlobalMouseMove = (e: MouseEvent) => {
      if (isDragging) {
        handleSliderMove(e.clientX)
      }
    }

    const handleGlobalMouseUp = () => {
      if (isDragging) {
        setIsDragging(false)
        checkVerification()
      }
    }

    if (isDragging) {
      document.addEventListener('mousemove', handleGlobalMouseMove)
      document.addEventListener('mouseup', handleGlobalMouseUp)
    }

    return () => {
      document.removeEventListener('mousemove', handleGlobalMouseMove)
      document.removeEventListener('mouseup', handleGlobalMouseUp)
    }
  }, [isDragging, handleSliderMove, checkVerification])

  // 初始化随机缺口位置
  useEffect(() => {
    if (isOpen) {
      setGapPosition(generateRandomGapPosition())
    }
  }, [isOpen])

  // 关闭时重置
  useEffect(() => {
    if (!isOpen) {
      resetVerification()
    }
  }, [isOpen, resetVerification])

  if (!isOpen) return null

  return (
    <div className="verify-modal-overlay">
      <div className="verify-modal">
        <div className="verify-modal-header">
          <h3 className="verify-title">安全验证</h3>
          <button className="verify-close" onClick={onClose}>
            ×
          </button>
        </div>
        
        <div className="verify-content">
          <div className="verify-description">
            <p>请完成下方滑块验证，以证明您不是机器人</p>
          </div>
          
          <div className="verify-puzzle-area">
            <div className="puzzle-background">
              <div className="puzzle-image">
                {/* 背景图片 */}
                <div className="puzzle-bg-image">
                  {/* 动态缺口位置 */}
                  <div 
                    className="puzzle-gap" 
                    style={{ left: `${gapPosition * 100}%` }}
                  ></div>
                </div>
                {/* 可拖动的拼图块 */}
                <div 
                  className="puzzle-piece"
                  style={{ left: `${sliderValue * 0.8}px` }}
                >
                  <div className="puzzle-piece-content"></div>
                </div>
              </div>
            </div>
            
            <div className="verify-slider-container">
              <div 
                className="slider-track"
                ref={sliderRef}
                onMouseDown={handleMouseDown}
                onTouchStart={handleTouchStart}
                onTouchMove={handleTouchMove}
                onTouchEnd={handleTouchEnd}
              >
                <div className="slider-thumb" style={{ left: `${sliderValue}px` }}>
                  <div className="slider-handle">
                    <span>→</span>
                  </div>
                </div>
                <div className="slider-text">
                  {verifyStatus === 'success' ? '验证成功' : 
                   verifyStatus === 'error' ? '验证失败，请重试' : 
                   '请拖动滑块，将拼图块移动到缺口位置'}
                </div>
              </div>
            </div>
          </div>
          
          <div className="verify-status">
            {verifyStatus === 'success' && (
              <div className="status-success">
                <span className="success-icon">✓</span>
                <div className="status-text">
                  <div className="status-title">验证成功！</div>
                  <div className="status-desc">拼图块已正确放置到缺口位置</div>
                </div>
              </div>
            )}
            {verifyStatus === 'error' && (
              <div className="status-error">
                <span className="error-icon">✗</span>
                <div className="status-text">
                  <div className="status-title">验证失败</div>
                  <div className="status-desc">拼图块未正确放置，请重试</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default VerifyModal